package cn.cdeden.knowledge.service.impl;

import cn.cdeden.knowledge.domain.LatelyUserTeam;
import cn.cdeden.knowledge.mapper.LatelyUserTeamMapper;
import cn.cdeden.knowledge.service.LatelyUserTeamService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Service
public class LatelyUserTeamServiceImpl extends ServiceImpl<LatelyUserTeamMapper, LatelyUserTeam> implements LatelyUserTeamService {

    @Override
    public Boolean addlatelyTeam(LatelyUserTeam latelyUserTeam) {
        latelyUserTeam.setUseTime(new Date());
        //新增数据之前判断是否已经有这个团队的数据了，如果有则是修改而不是新增
        LatelyUserTeam latelyUserTeam2 = getBaseMapper().selectOne(new QueryWrapper<LatelyUserTeam>().eq("user_id", latelyUserTeam.getUserId()).eq("team_id", latelyUserTeam.getTeamId()));
        if (latelyUserTeam2 == null) {
            int insert = getBaseMapper().insert(latelyUserTeam);
        } else {
            getBaseMapper().update(latelyUserTeam2, new UpdateWrapper<LatelyUserTeam>()
                    .eq("user_id", latelyUserTeam2.getUserId())
                    .eq("team_id", latelyUserTeam2.getTeamId())
                    .set("use_time", latelyUserTeam.getUseTime()));
        }

        //判断该用户的数据是否超过5条如果超过五条则删除最早的一条数据
        List<LatelyUserTeam> latelyUserTeamList = getBaseMapper().selectList(new QueryWrapper<LatelyUserTeam>().eq("user_id", latelyUserTeam.getUserId()));
        if (latelyUserTeamList.size() > 4) {
            LatelyUserTeam latelyUserTeam1 = latelyUserTeamList.stream().min(Comparator.comparing(LatelyUserTeam::getUseTime)).orElse(null);
            getBaseMapper().delete(new QueryWrapper<LatelyUserTeam>().eq("user_id", latelyUserTeam1.getUserId()).eq("use_time", latelyUserTeam1.getUseTime()));
        }
        return true;
    }
}
